/**
 * 
 */
package com.goktech.commons.excel.utils.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.goktech.commons.excel.utils.abs.AbstractReader;

/**
 * @author Administrator
 *
 */
public class ExcelImport extends AbstractReader<ExcelImport> {

	public ExcelImport(Class<?> clazz, InputStream is) {
		super(clazz, is);
	}

	public ExcelImport(Class<?> clazz, File file) throws FileNotFoundException {
		super(clazz, new FileInputStream(file));
	}

	public ExcelImport(Class<?> clazz, String path) throws FileNotFoundException {
		this(clazz, new File(path));
	}

	@Override
	public ExcelImport run() {
		try {

			workbook = new XSSFWorkbook(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Sheet sheet = this.workbook.getSheetAt(0);
		Iterator<Row> iterable = sheet.rowIterator();
		List<List<String>> list = new ArrayList<>();
		while (iterable.hasNext()) {
			Row row = iterable.next();
			Iterator<Cell> iterator = row.cellIterator();
			List<String> cellList = new ArrayList<>();
			while (iterator.hasNext()) {
				cellList.add(iterator.next().getStringCellValue());
			}
			if (cellList.size() > 0)
				list.add(cellList);
		}
		parser(list);
		return this.getSelf();
	}

	@Override
	public ExcelImport getSelf() {
		return this;
	}
	
	private void parser(List<List<String>> list) {
		for(int index = 0; index < list.size();index++) {
			if(index == 0) {
				initTitle(list.get(index));
			}else {
				putData(list.get(index));
			}
		}
	}

}
